//
//  ZWOauthViewController.swift
//  张伟的微博
//
//  Created by 伟 on 16/2/28.
//  Copyright © 2016年 伟. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZWOauthViewController: UIViewController {

    override func loadView() {
        self.view = webView
        setupItem()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        
        webView.delegate = self
      
        
        let request = NSURLRequest(URL: ZWNetWorwTool.sharedInstance.oauthLoginUrl())
        webView.loadRequest(request)
    
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func setupItem() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "stuffText")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelText")
    }
    
    func stuffText() {
        let js = "document.getElementById('userId').value='18627078987';document.getElementById('passwd').value='526107906'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    func cancelText() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
//懒加载
    lazy var webView :UIWebView = UIWebView()

}
//MARK: - webView代理
extension ZWOauthViewController: UIWebViewDelegate {
    //开始加载时
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载界面",maskType: SVProgressHUDMaskType.Black)
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
    }
    
    //webView询问我们是否去加载一个请求，true为加载，false为不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlstring = request.URL?.absoluteString
        print("\(urlstring)")
        //取到回调页的前缀，
        if urlstring!.hasPrefix(ZWNetWorwTool.sharedInstance.redirect_uri) {
            //截取url后面的地址
            let query = request.URL?.query
            let codestring = "code="
            if query!.hasPrefix(codestring) {
                //用户点击确定，取code
                let querystring = query! as NSString
                let code = querystring.substringFromIndex(codestring.characters.count)
                ZWUserAccountViewModel.sharedInstance.loadAccessToken(code, accessTokendidFinIshed: { (error) -> () in
                    if error != nil {
                        print("登录出错：\(error)")
                        SVProgressHUD.showErrorWithStatus("你的网络不给力")
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.cancelText()
                        })
                        
                        
                    }
                    
                    AppDelegate.outSwitchViewController(false)
                     // 账户保存成功了
                    self.cancelText()
                    
                    })
            } else {
                //撤出当前控制器
                
                cancelText()
            }
        return false
            
        }else {
             // 2.不是授权回调地址,直接加载这个请求
            return true
        }
    }
    
    
}

